package com.hspedu.mhl.utils;

/**
 * @author lianghao
 * @create 2022-07-11 17:28
 */

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtilsBYDruid {

    //(1):定义一个数据源,作为连接池
    private static DataSource ds;

    //(2):静态代码块  类加载的时候自动加载 而且只加载一次

    static {

        //获取配置文件的信息

        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src//druid.properties"));

            ds = DruidDataSourceFactory.createDataSource(properties);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //设置成静态的方法可以直接用类名进行调用
    public static Connection getConnection() throws SQLException {

        return ds.getConnection();
    }

    //关闭连接，是关闭java程序与连接池的连接 而并不是关闭与数据库的连接

    public static void close(ResultSet set, Statement statement,Connection connection){

        try {
            if(set != null){
                set.close();
            }

            if(statement != null){
                statement.close();
            }

            if(connection != null){
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


}


